package bm.com.ai.server.vector.service;

import bm.com.ai.server.vector.config.EmbeddingModelConfig;
import bm.com.ai.server.vector.config.QdrantConfig;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.store.embedding.EmbeddingMatch;
import dev.langchain4j.store.embedding.EmbeddingSearchRequest;
import dev.langchain4j.store.embedding.EmbeddingSearchResult;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.qdrant.QdrantEmbeddingStore;
import io.qdrant.client.QdrantClient;
import io.qdrant.client.QdrantGrpcClient;
import io.qdrant.client.grpc.Collections;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Qdrant向量存储服务
 */
@Slf4j
@Service
@Primary
public class QdrantVectorService implements EmbeddingStore<TextSegment> {

    private static Collections.Distance distance = Collections.Distance.Cosine;

    @Resource
    QdrantEmbeddingStore embeddingStore;

    @Resource
    EmbeddingModelConfig embeddingModelConfig;

    public List<EmbeddingMatch<TextSegment>> getEmbeddingMatch(String message) {
        try {

            Embedding queryEmbedding = embeddingModelConfig.embeddingModel().embed(message).content();
            EmbeddingSearchRequest embeddingSearchRequest = EmbeddingSearchRequest.builder()
                    .queryEmbedding(queryEmbedding)
                    .maxResults(1)
                    .build();

            return embeddingStore.search(embeddingSearchRequest).matches();

        } catch (Exception e) {
            log.error("Error: {}", e.getMessage() + " -- " + e.getCause());
        }
        return null;
    }

    @Override
    public String add(Embedding embedding) {
        return "";
    }

    @Override
    public void add(String s, Embedding embedding) {

    }

    @Override
    public String add(Embedding embedding, TextSegment textSegment) {
        return embeddingStore.add(embedding, textSegment);
    }

    @Override
    public List<String> addAll(List<Embedding> list) {
        return List.of();
    }

    /**
     * 批量添加嵌入
     */
    @Override
    public List<String> addAll(List<Embedding> embeddings, List<TextSegment> segments) {
        return embeddingStore.addAll(embeddings, segments);
    }

    @Override
    public EmbeddingSearchResult<TextSegment> search(EmbeddingSearchRequest embeddingSearchRequest) {
        return null;
    }

}